package com.xiaolong.websocket.core;

import com.xiaolong.websocket.context.UserInfo;
import com.xiaolong.websocket.context.WebSocketProcessor;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.util.Objects;

public class WebSocketConnectBeforeHandler extends ChannelInboundHandlerAdapter {


    private WebSocketProcessor webSocketProcessor;

    private String wsUri;

    public WebSocketConnectBeforeHandler(WebSocketProcessor webSocketProcessor, String wsUri) {
        this.webSocketProcessor = webSocketProcessor;
        this.wsUri = wsUri;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest) msg;
            if (!webSocketProcessor.supports(req)) {
                ctx.fireChannelRead(req.retain());
            }
            if (wsUri.equals(req.uri())) {
                //todo
            } else {
                sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED));
            }
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}